package com.jic.manager.controller.rest.store;

import com.alibaba.fastjson.JSONArray;
import com.jic.common.base.vo.PageResult;
import com.jic.common.base.vo.RestResult;
import com.jic.common.redis.RedisClientTemplate;
import com.jic.enums.RedisKey;
import com.jic.manager.api.rest.ManagerStoreApi;
import com.jic.manager.common.util.BeanUtil;
import com.jic.manager.entity.Mestore;
import com.jic.manager.entity.SysDept;
import com.jic.manager.mapper.MestoreMapper;
import com.jic.manager.mapper.SysDeptMapper;
import com.jic.manager.request.MemStoreRequest;
import com.jic.manager.request.MestorePageRequest;
import com.jic.manager.request.MestoreRequest;
import com.jic.manager.request.SysDeptRequest;
import com.jic.manager.request.rest.StoreRestRequest;
import com.jic.manager.response.MemMerchantInfoResponse;
import com.jic.manager.response.MemStoreResponse;
import com.jic.manager.response.MestoreResponse;
import com.jic.manager.response.StoreOfDept;
import com.jic.manager.service.MerchantService;
import com.jic.manager.service.MestoreService;
import com.jic.member.api.rest.MemberFavoriteManangeRestApi;
import com.jic.member.request.MemberFavoriteRestRequest;
import com.jic.member.request.MememberUserRequest;
import com.jic.product.after.api.ProductListApi;
import com.jic.product.after.request.MeStoreListRequest;
import com.jic.product.after.response.MeStoreListResponse;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

@SuppressWarnings("all")
@RestController
@RequestMapping("api/store")
public class ApiStoreController implements ManagerStoreApi {

    @Autowired
    private MestoreService memStoreService;
    @Autowired
    private MerchantService mMerchantService;

    @Resource
    private ProductListApi productListApi;
    @Autowired
    SysDeptMapper sysDeptMapper;

    @Resource
    private MestoreMapper mestoreMapper;

    @Autowired
    private RedisClientTemplate redisClientTemplate;

    @Resource
    MemberFavoriteManangeRestApi memberFavoriteManangeRestApi;

    /*查询店铺*/
    @PostMapping("getMemStoreInfo")
    public RestResult<MemStoreResponse> getMemStoreInfo(MemStoreRequest requestMemStore) {
        try {
            String token = requestMemStore.getToken();
            Long productId = requestMemStore.getProductId();
            Long storeId = requestMemStore.getStoreId();
            if (StringUtils.isEmpty(token)) {
                return RestResult.error("4000", "登录失效");
            }
            if (storeId == 0L || storeId == null || productId == 0L || productId == null) throw new Exception("必传参数为空");
            Mestore memStore = memStoreService.queryByPrimaryKey(storeId);
            if (memStore == null || memStore.getDeleteFlag().equals("Y"))
                throw new Exception("当前店铺不存在 storeId=" + storeId);
            MemStoreResponse memStoreResponse = new MemStoreResponse();
            BeanUtils.copyProperties(memStore, memStoreResponse);
            return RestResult.success(memStoreResponse);
        } catch (Exception e) {
            e.printStackTrace();
            return RestResult.error("9999", e.getLocalizedMessage());
        }
    }

    @Override
    public RestResult<MemStoreResponse> getStoreInfo(@RequestBody Long storeId) {
        try {
            Mestore memStore = memStoreService.queryByPrimaryKey(storeId);
            if (memStore == null || memStore.getDeleteFlag().equals("Y")) {
                throw new Exception("当前店铺不存在 storeId=" + storeId);
            }
            MemStoreResponse memStoreResponse = new MemStoreResponse();
            BeanUtils.copyProperties(memStore, memStoreResponse);
            return RestResult.success(memStoreResponse);
        } catch (Exception e) {
            e.printStackTrace();
            return RestResult.error("9999", e.getLocalizedMessage());
        }
    }

    /*查询商家*/

    @PostMapping("getShopList")
    @Override
    public RestResult<List<MemMerchantInfoResponse>> getShopList(@RequestParam List<Long> merchantIds) {
        List<MemMerchantInfoResponse> memMerchantInfoResponses = new ArrayList<MemMerchantInfoResponse>();
        for (Long merchantId : merchantIds) {
            MemMerchantInfoResponse memMerchantInfoResponse = mMerchantService.getShopList(merchantId);
            if(null!=memMerchantInfoResponse){
                memMerchantInfoResponses.add(memMerchantInfoResponse);
            }
        }
        return RestResult.success(memMerchantInfoResponses);
    }
    /*查询店铺*/

    @PostMapping("getStoreList")
    public RestResult<List<MeStoreListResponse>> getStoreList() {
        List<MeStoreListRequest> meStoreListResponseList = meStoreListResponseList = memStoreService.getStoreList();
        RestResult<List<MeStoreListResponse>> result = (RestResult<List<MeStoreListResponse>>) productListApi.queryMeStoreList(meStoreListResponseList);
        return result;
    }


    /*查询店铺*/
    @PostMapping("queryByPrimaryKey")
    @Override
    public com.jic.manager.response.Mestore queryByPrimaryKey(@RequestParam(value = "id") Long id) {
        Mestore mestore = memStoreService.queryByPrimaryKey(id);
        com.jic.manager.response.Mestore mestore1 = BeanUtil.copy(mestore,com.jic.manager.response.Mestore.class);
        return mestore1;
    }

    @Override
    public List<MemStoreResponse> getStoreInfoList(MestoreRequest request) {
        Mestore mestore = new Mestore();
        BeanUtils.copyProperties(request, mestore);
        List<MemStoreResponse> collect = memStoreService.query(mestore).stream().map(x -> {
            MemStoreResponse response = new MemStoreResponse();
            BeanUtils.copyProperties(x, response);
            return response;
        }).collect(Collectors.toList());
        return collect;
    }

    @Override
    public RestResult<List<StoreOfDept>> checkDeptByStoreIds(MestorePageRequest request) {
        List<Long> ids = request.getStoreIds();
        ArrayList<StoreOfDept> ofDepts = new ArrayList<>();
        if (CollectionUtils.isNotEmpty(ids)) {
            for (Long id : ids) {
                SysDept dept = new SysDept();
                dept.setBusinessId(id);
                SysDept byStoreId = sysDeptMapper.getDeptIdByStoreId(dept);
                StoreOfDept storeOfDept = new StoreOfDept();
                if (null != byStoreId) {
                    storeOfDept.setStoreId(id);
                    storeOfDept.setDeptId(byStoreId.getPid());
                } else {
                    storeOfDept.setStoreId(id);
                    storeOfDept.setDeptId(0L);
                }
                ofDepts.add(storeOfDept);
            }
        }
        return RestResult.success(ofDepts);
    }


    @Override
    @PostMapping("queryPage")
    public PageResult<MestoreResponse> queryPage(@RequestBody MestoreRequest mestore) {
        //计算下标
        int startIndex = (mestore.getStart() - 1) * mestore.getLimit();
        List<MestoreRequest> list = mestoreMapper.queryPage(startIndex, mestore.getLimit(), mestore);
        long count = mestoreMapper.queryPageCount(mestore);
        PageResult pageResult = new PageResult();
        pageResult.setRows(list);
        pageResult.setTotal(count);
        return pageResult;
    }


    @PostMapping("getDeptIdByMsId")
    @Override
    public Long getDeptIdByMsId(@RequestBody SysDeptRequest sysDept) {
        SysDept sysDept1 = new SysDept();
        sysDept1.setDeptType(sysDept.getDeptType());
        sysDept1.setId(sysDept.getId());
        return sysDeptMapper.getDeptIdByMsId(sysDept1);
    }


    /*根据店铺
     * 的编码查询店铺
     * */
    @ApiOperation("根据店铺编码查询店铺")
    @PostMapping("queryByStoreCode")
    public RestResult<List<MeStoreListResponse>> queryByStoreCode(@RequestBody StoreRestRequest storeRestRequest) {
        List<MeStoreListResponse> list = new ArrayList<>();
        list.add(memStoreService.queryByStoreCode(storeRestRequest.getStoreCode()));
        return RestResult.success(list);
    }


    @Override
    public List<MemMerchantInfoResponse> getMerchantList(List<Long> deptIds) {
        return mMerchantService.getMerchantList(deptIds);
    }


    /*查询店铺*/
    @ApiOperation("根据店铺id查询店铺信息")
    @PostMapping("getMemStoreInfoById")
    public RestResult<MemStoreResponse> getMemStoreInfoById(@RequestBody  MemStoreRequest requestMemStore) {
        try {
            String userStr = redisClientTemplate.get(RedisKey.H5_LOGIN_TOKEN_.getName() + requestMemStore.getToken());
            MememberUserRequest mMember = JSONArray.parseObject(userStr, MememberUserRequest.class);
            Mestore memStore = memStoreService.queryByPrimaryKey(requestMemStore.getId());
            if (memStore == null || memStore.getDeleteFlag().equals("Y")){
                throw new Exception("当前店铺不存在 storeId=" + requestMemStore.getId());
            }
            MemStoreResponse memStoreResponse = BeanUtil.copy(memStore, MemStoreResponse.class);
            if(mMember ==null){
                memStoreResponse.setIsFavorite(0);
            }else{
                MemberFavoriteRestRequest favority = new MemberFavoriteRestRequest();
                favority.setEntityId(memStore.getId());
                favority.setMemberId(mMember.getId());
                Boolean boosStore = memberFavoriteManangeRestApi.queryFollowersByEntityId(favority);
                RestResult restResult = memberFavoriteManangeRestApi.countFollowersByEntityId(new MemberFavoriteRestRequest(){{
                   // setMemberId(mMember.getId());
                    setEntityId(memStore.getId());
                    setEntityType(2);
                }});
                if(boosStore){
                    memStoreResponse.setIsFavorite(1);
                }else {
                    memStoreResponse.setIsFavorite(0);
                }
                if(null != restResult.getData()){
                    memStoreResponse.setFavoriteNum(Integer.valueOf(restResult.getData().toString()));
                }
            }
            return RestResult.success(memStoreResponse);
        } catch (Exception e) {
            e.printStackTrace();
            return RestResult.error("9999", e.getLocalizedMessage());
        }
    }
}
